<template>
  <div>
    <form>
      <div class="form-group">
        <label for="comment">粘贴Excel内容:</label>
        <textarea
          class="form-control"
          rows="20"
          style="resize: none"
          v-model="raw"
        ></textarea>
      </div>
      <div class="alert alert-danger" v-for="(err, id) in errInfo" :key="id">
        <button type="button" class="close" @click="errInfo.splice(id, 1)">
          &times;
        </button>
        <strong>错误{{ id + 1 }}：</strong>
        {{ err }}
      </div>
      <p class="text-muted small">
        在
        <strong>Excel</strong>中按 <mark>Ctrl+A</mark>、 <mark>Ctrl+C</mark>，在
        <strong>文本框</strong>中按 <mark>Ctrl+V</mark>，点击导入。
      </p>
    </form>
    <form v-if="adminLevel >= 9">
      <div class="btn-group">
        <button type="button" class="btn btn-dark" @click="getArray()">
          导入
        </button>
        <button type="button" class="btn btn-dark" @click="cleanData()">
          清空
        </button>
      </div>
      <span class="space-1em"></span>
      <div class="form-check form-check-inline">
        <label class="form-check-label">
          <input
            type="checkbox"
            class="form-check-input"
            v-model="clean"
          />删除未匹配数据
        </label>
      </div>
    </form>
    <form v-else>
      <div class="alert alert-warning">
        <strong>此操作有危险！</strong>根据当前的权限设置，您不能进行此操作。
      </div>
    </form>
    <maskView v-if="optData">
      <div v-if="countAll == 0">
        <h4>无需操作</h4>
        <p>
          识别到
          <strong>{{ newData.basic_data.length }}</strong>
          人的
          <strong>{{
            newData.basic_data.length + newData.extention_data.length
          }}</strong>
          条有效数据，与现有数据
          <strong>完全一致</strong>，无需导入。
        </p>
        <button type="button" class="btn btn-dark" @click="cleanData()">
          好的
        </button>
      </div>
      <div v-if="countAll > 0">
        <h4>确定导入吗</h4>
        <p>
          识别到
          <strong>{{ newData.basic_data.length }}</strong>
          人的
          <strong>{{
            newData.basic_data.length + newData.extention_data.length
          }}</strong>
          条有效数据，导入这些数据将会：
        </p>
        <ul>
          <li v-if="countAdd > 0">
            注册
            <strong>{{ countAdd }}</strong
            >人员信息；
          </li>
          <li v-if="countRemove > 0">
            注销
            <strong>{{ countRemove }}</strong
            >人员信息；
          </li>
          <li v-if="countInsert > 0">
            增加
            <strong>{{ countInsert }}</strong
            >项新数据；
          </li>
          <li v-if="countUpdate > 0">
            修改
            <strong>{{ countUpdate }}</strong
            >项现有数据；
          </li>
          <li v-if="countDelete > 0">
            删除
            <strong>{{ countDelete }}</strong
            >项现有数据；
          </li>
        </ul>
        <p>
          <button
            type="button"
            class="btn btn btn-link"
            @click="showInfo = true"
          >
            查看备注
          </button>
          <button
            type="button"
            v-show="isDev"
            class="btn btn btn-link"
            @click="showData = true"
          >
            查看数据
          </button>
        </p>
        <div class="btn-group">
          <button type="button" class="btn btn-dark" @click="doImport()">
            确定
          </button>
          <button type="button" class="btn btn-dark" @click="cleanData()">
            取消
          </button>
        </div>
      </div>
    </maskView>
    <infoView
      v-if="showInfo"
      :title="'操作备注'"
      :remark="'以下内容为 JavaScript Object'"
      :content="optInfo"
      @close="showInfo = false"
    ></infoView>
    <infoView
      v-if="showData"
      :title="'后端的数据'"
      :remark="'以下内容为 JavaScript Object'"
      :content="optData"
      @close="showData = false"
    ></infoView>
  </div>
</template>

<script>
import maskView from "@/views/maskView";
import infoView from "@/views/maskView/infoView.vue";
export default {
  name: "importView",
  components: {
    maskView,
    infoView,
  },
  data() {
    return {
      raw: "",
      clean: false,
      response: null,
      oldData: null,
      newData: null,
      optData: null,
      showData: false,
      showInfo: false,
      errInfo: new Array(),
      optInfo: null,
    };
  },
  computed: {
    adminLevel() {
      if (this.$store.state.securityData == null) return 0;
      else return this.$store.state.securityData.adminPIMS;
    },
    countAdd() {
      if (this.optData) {
        return this.optData.to_insert.basic_data.length;
      } else {
        return 0;
      }
    },
    countRemove() {
      if (this.optData) {
        return this.optData.to_delete.basic_data.length;
      } else {
        return 0;
      }
    },
    countUpdate() {
      if (this.optData) {
        return (
          this.optData.to_update.basic_data.length +
          this.optData.to_update.extention_data.length
        );
      } else {
        return 0;
      }
    },
    countInsert() {
      if (this.optData) {
        return (
          this.optData.to_insert.basic_data.length +
          this.optData.to_insert.extention_data.length
        );
      } else {
        return 0;
      }
    },
    countDelete() {
      if (this.optData) {
        return (
          this.optData.to_delete.basic_data.length +
          this.optData.to_delete.extention_data.length
        );
      } else {
        return 0;
      }
    },
    countAll() {
      if (this.optData) {
        return (
          this.optData.to_insert.basic_data.length +
          this.optData.to_insert.extention_data.length +
          this.optData.to_update.basic_data.length +
          this.optData.to_update.extention_data.length +
          this.optData.to_delete.basic_data.length +
          this.optData.to_delete.extention_data.length
        );
      } else {
        return 0;
      }
    },
  },
  methods: {
    doImport() {
      this.$store.commit("setLoading", true);
      let action = "import";
      this.axios
        .post("api/", {
          action: action,
          payload: {
            login_data: this.$store.state.loginData,
            operate_data: this.optData,
          },
        })
        .then((response) => {
          if (this.isDev) window.console.log(response.data);
          this.cleanData();
          this.$store.commit("setLoading", false);
        });
    },
    resetData() {
      this.errInfo = new Array();
      this.newData = null;
      this.oldData = null;
      this.optData = null;
      this.optInfo = null;
    },
    getArray() {
      this.resetData();
      this.$store.commit("setLoading", true);
      if (this.raw.length <= 675) {
        this.errInfo.push("输入的内容太少了");
        this.$store.commit("setLoading", false);
        return null;
      }
      this.$store.commit("setLoading", true);
      let lineData = this.raw.split(/\n/);
      let titleData = lineData[0].split(/\t/);
      let basicData = new Array();
      let extentionData = new Array();
      for (let line = 1; line < lineData.length; line++) {
        let rowData = lineData[line].split(/\t/);
        let basic = {
          serial_number: 0,
          name: "",
          clientName: "",
          number: 0,
          sex: "",
          birth_date: "",
          id_number: "",
          nation: "",
        };
        let extention = new Array();
        for (let row = 0; row < rowData.length; row++) {
          if (rowData[row].length > 0) {
            if (titleData[row] == "编号") {
              basic.serial_number = Number(rowData[row]);
            } else if (titleData[row] == "姓名") {
              basic.clientName = rowData[row];
              basic.name = rowData[row]
                .replace(/1/g, "")
                .replace(/2/g, "")
                .replace(/3/g, "");
            } else if (titleData[row] == "V人员工号") {
              basic.number = Number(rowData[row]);
            } else if (titleData[row] == "性别") {
              basic.sex = rowData[row];
            } else if (titleData[row] == "出生日期") {
              basic.birth_date = rowData[row];
            } else if (titleData[row] == "身份证号") {
              basic.id_number = rowData[row];
            } else if (titleData[row] == "民族") {
              basic.nation = rowData[row];
            } else {
              let title = titleData[row].replace(/V/g, "");
              if (
                title != "年龄" &&
                title != "本单位工龄" &&
                title != "总工龄" &&
                title != ""
              ) {
                extention.push({
                  clientName: "",
                  number: 0,
                  itemTitle: title,
                  itemValue: rowData[row],
                  timeStamp: 0,
                  status: 0,
                });
              }
            }
          }
        }
        for (let cell = 0; cell < extention.length; cell++) {
          extention[cell].clientName = basic.clientName;
          extention[cell].number = basic.number;
          extention[cell].timeStamp = new Date().getTime();
          extention[cell].status = 9;
          extentionData.push(extention[cell]);
        }
        if (basic.number != 0) basicData.push(basic);
      }
      if (!basicData && basicData.length == 0) {
        this.errInfo.push("未能解析出任何内容");
        this.$store.commit("setLoading", false);
        return null;
      }
      this.$store.commit("setLoading", false);

      // return {
      //     basic_data: basicData,
      //     extention_data: extentionData
      // };
      this.newData = {
        basic_data: basicData,
        extention_data: extentionData,
      };
      this.getData();
    },
    getData() {
      this.$store.commit("setLoading", true);
      this.axios
        .post("api/", {
          action: "export",
          payload: { login_data: this.$store.state.loginData },
        })
        .then((response) => {
          if (this.isDev) window.console.log(response.data);
          if (response.data.result != "success") {
            this.errInfo.push("读取数据库失败");
            // this.errInfo.push("导入失败");
            this.$store.commit("setLoading", false);
            return null;
          }
          this.oldData = response.data.content;
          // this.newData = this.getArray();
          if (this.isDev) window.console.log(this.oldData);
          if (this.isDev) window.console.log(this.newData);
          if (this.oldData && this.newData) {
            this.optData = this.doCompare();
            if (this.isDev) window.console.log(this.optData);
          } else {
            // this.errInfo.push("导入失败");
          }
          this.$store.commit("setLoading", false);
        });
    },
    cleanData() {
      this.raw = "";
      this.newData = null;
      this.oldData = null;
      this.errInfo = new Array();
      this.optData = null;
      this.showConfirm = false;
      this.$store.commit("setLoading", false);
    },
    doCompare() {
      this.$store.commit("setLoading", true);
      let to_update = {
        basic_data: new Array(),
        extention_data: new Array(),
      };
      let to_insert = {
        basic_data: new Array(),
        extention_data: new Array(),
      };
      let to_delete = {
        basic_data: new Array(),
        extention_data: new Array(),
      };
      let optInfo = new Array();
      //basic_data compare
      for (let i = 0; i < this.newData.basic_data.length; i++) {
        let isNew = true;
        for (let j = 0; j < this.oldData.basic_data.length; j++) {
          //if basic_data is already existed
          if (
            this.newData.basic_data[i].number ==
            this.oldData.basic_data[j].number
          ) {
            isNew = false;
            //if basic_data are equaled
            if (
              this.newData.basic_data[i].sex !=
                this.oldData.basic_data[j].sex ||
              this.newData.basic_data[i].birth_date !=
                this.oldData.basic_data[j].birth_date ||
              this.newData.basic_data[i].id_number !=
                this.oldData.basic_data[j].id_number ||
              this.newData.basic_data[i].nation !=
                this.oldData.basic_data[j].nation ||
              this.newData.basic_data[i].clientName !=
                this.oldData.basic_data[j].clientName
            ) {
              to_update.basic_data.push(this.newData.basic_data[i]);
              if (
                this.newData.basic_data[i].sex != this.oldData.basic_data[j].sex
              ) {
                optInfo.push({
                  action: "修改数据",
                  name: this.newData.basic_data[i].clientName,
                  number: this.newData.basic_data[i].number,
                  item: "性别",
                  value_old: this.oldData.basic_data[j].sex,
                  value: this.oldData.basic_data[j].sex,
                });
              }
              if (
                this.newData.basic_data[i].birth_date !=
                this.oldData.basic_data[j].birth_date
              ) {
                optInfo.push({
                  action: "修改数据",
                  name: this.newData.basic_data[i].clientName,
                  number: this.newData.basic_data[i].number,
                  item: "出生日期",
                  value_old: this.oldData.basic_data[j].birth_date,
                  value: this.oldData.basic_data[j].birth_date,
                });
              }
              if (
                this.newData.basic_data[i].id_number !=
                this.oldData.basic_data[j].id_number
              ) {
                optInfo.push({
                  action: "修改数据",
                  name: this.newData.basic_data[i].clientName,
                  number: this.newData.basic_data[i].number,
                  item: "身份证号",
                  value_old: this.oldData.basic_data[j].id_number,
                  value: this.oldData.basic_data[j].id_number,
                });
              }
              if (
                this.newData.basic_data[i].nation !=
                this.oldData.basic_data[j].nation
              ) {
                optInfo.push({
                  action: "修改数据",
                  name: this.newData.basic_data[i].clientName,
                  number: this.newData.basic_data[i].number,
                  item: "民族",
                  value_old: this.oldData.basic_data[j].clientName,
                  value: this.oldData.basic_data[j].clientName,
                });
              }
            }
            break;
          }
        }
        if (isNew) {
          to_insert.basic_data.push(this.newData.basic_data[i]);
          optInfo.push({
            action: "新建用户",
            name: this.newData.basic_data[i].clientName,
            number: this.newData.basic_data[i].number,
          });
          optInfo.push({
            action: "添加数据",
            name: this.newData.basic_data[i].clientName,
            number: this.newData.basic_data[i].number,
            item: "性别",
            value: this.newData.basic_data[i].sex,
          });
          optInfo.push({
            action: "添加数据",
            name: this.newData.basic_data[i].clientName,
            number: this.newData.basic_data[i].number,
            item: "出生日期",
            value: this.newData.basic_data[i].birth_date,
          });
          optInfo.push({
            name: this.newData.basic_data[i].clientName,
            number: this.newData.basic_data[i].number,
            item: "身份证号",
            value: this.newData.basic_data[i].id_number,
          });
          optInfo.push({
            action: "添加数据",
            name: this.newData.basic_data[i].clientName,
            number: this.newData.basic_data[i].number,
            item: "民族",
            value: this.newData.basic_data[i].nation,
          });
        }
      }
      //extention_data compare
      for (let i = 0; i < this.newData.extention_data.length; i++) {
        let isNew = true;
        for (let j = 0; j < this.oldData.extention_data.length; j++) {
          //if extention_data is existed
          if (
            this.newData.extention_data[i].number ==
              this.oldData.extention_data[j].number &&
            this.newData.extention_data[i].itemTitle ==
              this.oldData.extention_data[j].itemTitle
          ) {
            //if extention_data are same
            if (
              this.newData.extention_data[i].itemValue !=
              this.oldData.extention_data[j].itemValue
            ) {
              to_update.extention_data.push(this.newData.extention_data[i]);
              optInfo.push({
                action: "修改数据",
                name: this.newData.extention_data[i].clientName,
                number: this.newData.extention_data[i].number,
                item: this.newData.extention_data[i].itemTitle,
                value_old: this.oldData.extention_data[j].itemValue,
                value: this.newData.extention_data[i].itemValue,
              });
            }
            isNew = false;
            break;
          }
        }
        if (isNew) {
          to_insert.extention_data.push(this.newData.extention_data[i]);
          optInfo.push({
            action: "添加数据",
            name: this.newData.extention_data[i].clientName,
            number: this.newData.extention_data[i].number,
            item: this.newData.extention_data[i].itemTitle,
            value: this.newData.extention_data[i].itemValue,
          });
        }
      }
      //if dispose
      if (this.clean) {
        //basic data disposed
        let disposedList = new Array();
        for (let i = 0; i < this.oldData.basic_data.length; i++) {
          let isDisposed = true;
          for (let j = 0; j < this.newData.basic_data.length; j++) {
            if (
              this.newData.basic_data[j].number ==
              this.oldData.basic_data[i].number
            ) {
              isDisposed = false;
              break;
            }
          }
          if (isDisposed) {
            disposedList.push(this.oldData.basic_data[i].number);
            to_delete.basic_data.push(this.oldData.basic_data[i]);
            optInfo.push({
              action: "注销用户",
              name: this.oldData.basic_data[i].clientName,
              number: this.oldData.basic_data[i].number,
            });
          }
        }
        //extention data to_delete
        for (let i = 0; i < this.oldData.extention_data.length; i++) {
          let isDisposed = true;
          if (disposedList.includes(this.oldData.extention_data[i].number)) {
            for (let j = 0; j < this.newData.extention_data.length; j++) {
              if (
                this.newData.extention_data[j].number ==
                  this.oldData.extention_data[i].number &&
                this.newData.extention_data[j].itemTitle ==
                  this.oldData.extention_data[i].itemTitle
              ) {
                isDisposed = false;
                break;
              }
            }
          }
          if (isDisposed) {
            to_delete.extention_data.push(this.oldData.extention_data[i]);
            optInfo.push({
              action: "删除信息",
              name: this.oldData.extention_data[i].clientName,
              number: this.oldData.extention_data[i].number,
              item: this.oldData.extention_data[i].itemTitle,
              value_old: this.oldData.extention_data[i].itemValue,
              value: "无",
            });
          }
        }
      }
      this.$store.commit("setLoading", false);
      this.optInfo = optInfo;
      return {
        to_update: to_update,
        to_insert: to_insert,
        to_delete: to_delete,
      };
    },
  },
};
</script>

<style scoped>
.alert {
  padding: 0.25em 1em;
  margin: 0.5em 0;
}
</style>